#include "hc05.h"

#include "err.h"
#include "oled.h"
#include "usart.h"

Hc05_HandleTypeDef *global;

int Hc05_Init(Hc05_HandleTypeDef *handle) {
  handle->p_read = handle->p_write = handle->bufin;
  handle->bufout[0] = 0;
  global = handle;
  HAL_UART_Init(&huart2);
  HAL_UART_Receive_IT(&huart2, handle->p_write, 1);
  return 0;
}

uint8_t Hc05_Empty(Hc05_HandleTypeDef *handle) {
  return handle->p_read == handle->p_write;
}

uint8_t Hc05_Read(Hc05_HandleTypeDef *handle) {
  if (Hc05_Empty(handle)) return 0;
  uint8_t ret = *handle->p_read;
  handle->p_read++;
  if (handle->p_read - handle->bufin >= HC05_BUFFER_SIZE) {
    handle->p_read = handle->bufin;
  }
  return ret;
}

uint8_t Hc05_SetGlobal(Hc05_HandleTypeDef *handle) {
  if (global == handle) return 1;
  global = handle;
  return 0;
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
  Oled_ShowStringSmall(0, 1, "callback");
  Err_Off();
  if (huart->Instance == USART2) {
    global->p_write++;
    if (global->p_write - global->p_read >= HC05_BUFFER_SIZE)
      global->p_write = global->bufin;
    HAL_UART_Receive_IT(&huart2, global->p_write, 1);
  }
}
